/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-09-02
 */
package main

//带参数的定时任务
import (
	"lanfengye/base/rpcServer"
	"sync"
)

var waitGroup sync.WaitGroup

func main() {
	defer func() {
		Log.Warn("出现异常")
		if err := recover(); err != nil {
			Log.Error("异常恢复错误：", err)
		}
		Log.Error("异常恢复")
	}()
	//初始化任务
	initJobs()
	c.Start()

	Log.Info("启动成功")

	waitGroup.Add(1)
	go initRpc(&waitGroup)

	waitGroup.Wait()
}

//初始化任务
func initJobs() {
	//从数据库进行初始化
	t := GetTask()
	taskList := t.GetListAll()
	PutTask(t)

	Log.Info("开始初始化%+v", taskList)

	if taskList == nil {
		Log.Notice("初始化任务列表为空")
		return
	}
	//添加所有任务
	for _, v := range taskList {
		AddJob(v)
	}
}

//初始化RPC控制
func initRpc(w *sync.WaitGroup) {
	defer w.Done()
	service,err:=rpcServer.NewRpcServer(C.Http.Listen,"http")
	if err!=nil{
		Log.Error("创建rpc服务端失败：%s",err.Error())
		return
	}
	defer service.Close()

	//service := rpc.NewHTTPService()
	service.AddFunction("add", addJob)
	service.AddFunction("remove", removeJob)
	service.AddFunction("edit", editJob)
	service.AddFunction("jobList", jobList)
	//err := http.ListenAndServe(":"+C.Http.Listen, service)
	err=service.Start()

	if err != nil {
		Log.Error("启动RPC接口失败,端口:" + C.Http.Listen + "," + err.Error())
	}
}
